from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
import os
from django.shortcuts import render
from django.db import connection
import requests
import json
from django.shortcuts import render
from django.db import connection
import requests
import json


def delete_html_txt_png_file(file_path):
    try:
        os.remove(file_path)
        return True
    except:
        print("找不到文件")
        return False


@csrf_exempt
def d_index(request, html_file_id):
    print(html_file_id)  # 前端返回文件 id

    arrrr = []
    # 需要删除三种文件 : .html   .txt   .png
    html_path = os.path.abspath(__file__).split("delete.py")[0] + "templates\html_demo\\" + html_file_id + ".html"
    print(html_path)
    del_html = delete_html_txt_png_file(html_path)
    arrrr.append(del_html)

    txt_path = os.path.abspath(__file__).split("delete.py")[0] + "templates\html_demo\\" + html_file_id + ".txt"
    print(txt_path)
    del_txt = delete_html_txt_png_file(txt_path)
    arrrr.append(del_txt)

    img_png_path = os.path.abspath(__file__).split("delete.py")[0] + "static\img\\" + html_file_id + ".png"
    print(img_png_path)
    del_png = delete_html_txt_png_file(img_png_path)
    arrrr.append(del_png)

    str_list = [str(item) for item in arrrr]
    # 使用join()方法连接字符串
    return_string = ', '.join(str_list)
    print(return_string)
    # return html_file_id
    # return HttpResponse(html_file_id, content_type="application/json")
    return HttpResponse("<h1>"+  return_string  +"</h1>")

    # if request.method == 'POST':
    #     data={}
    #     print("哈哈哈哈\n哈哈哈哈\n哈哈哈哈")
    #     print(request.body)       # b'user-name=1&user-email=1%40q.com'
    #     html_file_name = request.POST.get('html_file_name')
    #     html_file_content = request.POST.get('html_file_content')
    #     print(html_file_name)
    #     print(html_file_content)
    #     file_path=os.path.abspath(__file__).split("add.py")[0] + "templates\html_demo\\" + html_file_name + ".html"
    #     print(file_path) # C:\Users\yxb\Desktop\html_demo\yxb\templates\html_demo\111.html
    #     try:
    #         with open(file_path, "r", encoding="utf-8") as f:
    #             string = f.read()
    #             print("文件存在")
    #             data["return_text"]='file_exist'
    #     except:
    #         print("文件不存在")
    #         with open(file_path, "w", encoding="utf-8") as f:
    #             f.write(html_file_content)
    #             data["return_text"]='new_file_success'
    #
    # data = json.dumps(data)
    # return HttpResponse(data, content_type="application/json")
